package com.itheima.interceptors;

import org.apache.commons.lang.StringUtils;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import java.util.Map;

/**
 * @Description: 进入<MessageHandler>之前的 拦截器
 * @Date :2019-10-26 14:00
 * @Author : yuan_he_song
 */
@Component
public class WebsocketInterceptor implements HandshakeInterceptor {

    @Override /** 在客户端和服务端握手(连接)之前,进入<MessageHandler>之前 */
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response,
                                   WebSocketHandler socketHandler, Map<String, Object> map) throws Exception {
        /**
         * 用户点击好友列表,打开聊天对话框,建立websocket连接
         * 获取请求服务端的地址  ws://127.0.0.1/websocket/1
         */
        String path = request.getURI().getPath(); /**--> websocket/1 <--*/
        String[] split = path.split("/");
        if(split.length != 3){
            return false;
        }
        if(!StringUtils.isNumeric(split[2])){
            return false;
        }
        /** 把用户id存入map中 */
        map.put("uid",Integer.parseInt(split[2]));
        return true;
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response,
                                        WebSocketHandler webSocketHandler, Exception e) {

    }
}
